package cn.tedu.micro.demo.order.service.impl;

import cn.tedu.micro.demo.common.protocol.JsonResult;
import cn.tedu.micro.demo.common.vo.GunInfoVO;
import cn.tedu.micro.demo.order.client.DeviceClient;
import cn.tedu.micro.demo.order.dao.repository.OrderRepository;
import cn.tedu.micro.demo.order.po.OrderInfoPO;
import cn.tedu.micro.demo.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private DeviceClient deviceClient;
    @Override
    public String saveOrder(Integer userId, Integer gunId) {
        checkGunStatus(gunId);
        String billId = UUID.randomUUID().toString().replace("-", "");
        OrderInfoPO orderInfoPO = new OrderInfoPO();
        orderInfoPO.setUserId(userId);
        orderInfoPO.setBillId(billId);
        orderInfoPO.setGunId(gunId);
        Date now = new Date();
        orderInfoPO.setCreateTime(now);
        orderInfoPO.setUpdateTime(now);
        orderRepository.saveOrder(orderInfoPO);
        return billId;
    }
    private void checkGunStatus(Integer gunId) {
        log.info("检查枪支状态，gunId={}",gunId);
        JsonResult<GunInfoVO> result = deviceClient.getGunStatus(gunId);
        if(result.getCode()==0){
            if(result.getData()!=null){
                GunInfoVO data = result.getData();
                if(data.getStatus()==1){
                    return;
                }
            }
        }
        throw new RuntimeException("枪支状态异常");
    }
}
